package com.bigzero.workflow.modules.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigzero.workflow.common.exception.WorkflowException;
import com.bigzero.workflow.common.utils.JwtUtil;
import com.bigzero.workflow.modules.system.dao.UserDao;
import com.bigzero.workflow.modules.system.dao.UserRoleDao;
import com.bigzero.workflow.modules.system.dto.LoginDto;
import com.bigzero.workflow.modules.system.dto.UserDto;
import com.bigzero.workflow.modules.system.entity.RoleEntity;
import com.bigzero.workflow.modules.system.entity.UserEntity;
import com.bigzero.workflow.modules.system.entity.UserRoleEntity;
import com.bigzero.workflow.modules.system.query.UserQuery;
import com.bigzero.workflow.modules.system.service.UserService;
import com.bigzero.workflow.modules.system.vo.UserActivitiVo;
import com.bigzero.workflow.modules.system.vo.UserVo;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 用户实现类
 * @Author: fanxinxiong
 * @Date: 2025-02-11 14:48:00
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService{

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserRoleDao userRoleDao;

    /**
     * 系统用户分页列表
     *
     * @param query 分页参数
     * @return 列表
     */
    @Override
    public List<UserVo> queryPage(UserQuery query) {
        List<UserVo> voList = this.baseMapper.queryPage(query);
        if(!CollectionUtils.isEmpty(voList)){
            String roleName;
            for(UserVo vo : voList){
                roleName = userRoleDao.selectRoleNameByUserId(vo.getId());
                vo.setRoleName(roleName);
            }
        }
        return voList;
    }

    /**
     * 根据用户名查找用户activiti vo
     * @param username 用户名
     * @return UserActivitiVo
     */
    public UserActivitiVo getUserActivitiVoByUsername(String username){
        UserActivitiVo vo = new UserActivitiVo();

        LambdaQueryWrapper<UserEntity> lqw = new QueryWrapper<UserEntity>().lambda();
        lqw.eq(UserEntity :: getUsername, username);
        List<UserEntity> userEntityList = baseMapper.selectList(lqw);
        if(!CollectionUtils.isEmpty(userEntityList)){
            UserEntity userEntity = userEntityList.get(0);
            BeanUtils.copyProperties(userEntity, vo);

            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("userId", userEntity.getId());//用户id
            //角色实体集合
            List<RoleEntity> roleEntityList = userRoleDao.selectRoleEntityListByMap(map);
            roleEntityList = Optional.ofNullable(roleEntityList).orElse(new ArrayList<>());
            vo.setRoleList(roleEntityList);
        }
        return vo;
    }

    /**
     * 登录
     * @param loginDto 登录dto
     * @return UserVo
     */
    public JSONObject login(LoginDto loginDto){
        String password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes(StandardCharsets.UTF_8));
        UserVo userVo = this.baseMapper.selectUserVoByUsernameAndPassword(loginDto.getUserName(), password);
        if(userVo == null){
            throw new WorkflowException("用户或者密码错误!");
        }
        userVo.setPassword("***");

        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(userVo));

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userVo.getId());//主键
        claims.put("deptId", userVo.getDeptId());//部门id
        claims.put("username", userVo.getUsername());//用户名
        claims.put("account", userVo.getAccount());//姓名
        claims.put("email", userVo.getEmail());//邮箱
        claims.put("mobile", userVo.getMobile());//手机号
        claims.put("isSys", userVo.getIsSys());//是否是系统内置,1:是,0:否
        claims.put("deptName", userVo.getDeptName());//部门名称

        //创建token令牌
        String token = jwtUtil.createToken(claims);

        jsonObject.put("token", token);//token令牌
        return jsonObject;
    }

    /**
     * 新增或者修改
     * @param userDto entity实体
     * @return int
     */
    public int insertOrUpdate(UserDto userDto){
        UserEntity entity = new UserEntity();
        if(StringUtils.isNotEmpty(userDto.getId())) {
            UserEntity user = this.baseMapper.selectById(userDto.getId());
            if(user == null){
                throw new WorkflowException("未知数据");
            }
            if(user.getIsSys() == 1){
                throw new WorkflowException("系统内置不能修改!");
            }
            userDto.setPassword("***".equals(userDto.getPassword()) ? null : userDto.getPassword());
        }
        String password = (StringUtils.isEmpty(userDto.getPassword())) ? userDto.getPassword() : DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes(StandardCharsets.UTF_8));
        BeanUtils.copyProperties(userDto, entity);
        entity.setPassword(password);
        Date date = new Date();
        if(StringUtils.isEmpty(entity.getId())){
            entity.setCreateTime(date);
        }
        entity.setUpdateTime(date);

        if(StringUtils.isEmpty(entity.getId())){
            this.baseMapper.insert(entity);
        }else{
            LambdaQueryWrapper<UserRoleEntity> lqw = new LambdaQueryWrapper<UserRoleEntity>();
            lqw.eq(UserRoleEntity :: getUserId, entity.getId());
            userRoleDao.delete(lqw);
            this.baseMapper.updateById(entity);
        }

        if(!CollectionUtils.isEmpty(userDto.getRoleIdList())){
            List<UserRoleEntity> list = new ArrayList<>();
            for(String roleId : userDto.getRoleIdList()){
                UserRoleEntity ure = new UserRoleEntity();
                ure.setUserId(entity.getId());
                ure.setRoleId(roleId);
                list.add(ure);
            }
            userRoleDao.insert(list);
        }
        return 1;
    }

    /**
     * 根据id获取vo对象
     * @param id 主键id
     * @return UserVo
     */
    public UserVo getVoById(String id){
        UserEntity entity = baseMapper.selectById(id);
        if(Objects.isNull(entity)){
            return null;
        }
        UserVo vo = new UserVo();
        BeanUtils.copyProperties(entity, vo);
        vo.setPassword("***");

        //根据用户id查询角色id集合
        List<String> roleIdList = userRoleDao.selectRoleIdListByUserId(vo.getId());
        vo.setRoleIdList(roleIdList);
        return vo;
    }

    /**
     * 根据id删除用户
     * @param id 主键id
     * @return int
     */
    public int deleteById(String id){
        UserEntity user = baseMapper.selectById(id);
        if(user == null){
            throw new WorkflowException("未知数据");
        }
        if(user.getIsSys() == 1){
            throw new WorkflowException("系统内置不能删除!");
        }
        LambdaQueryWrapper<UserRoleEntity> lqw = new LambdaQueryWrapper<UserRoleEntity>();
        lqw.eq(UserRoleEntity :: getUserId, id);
        userRoleDao.delete(lqw);
        return baseMapper.deleteById(id);
    }
}
